extends Node
@onready var bgm:AudioStreamPlayer2D=$BGM

# 音频设置：设置名称，默认值
var Bus=[    
    { name = 'master', value = 0.5 },
    { name = 'soud', value = 1 },
    { name = 'bgm', value = 1 },
]

# 播放背景音乐
func playBgm(steam:AudioStream)->void:
    if bgm.stream==steam and bgm.playing:return

    bgm.stream=steam
    bgm.play()

# 播放音效
func play(_name:String)->void:
    var sound:=get_node(_name) as AudioStreamPlayer2D
    if !sound:return
    sound.play()

# 将ui上所有交互节点绑定音效事件
func bindEvent(node:Node)->void:
    var button:=node as Button
    if button:
        button.button_down.connect(play.bind('Press'))
        button.focus_entered.connect(play.bind('Focus'))
        button.mouse_entered.connect(button.grab_focus)

    var slider:=node as Slider
    if slider:
        slider.value_changed.connect(play.bind('Press').unbind(1))
        slider.focus_entered.connect(play.bind('Focus'))
        slider.mouse_entered.connect(slider.grab_focus)

    # 递归处理子节点
    for child in node.get_children():
        bindEvent(child)

# 获取音量
func getVolume(busIndex:int)->float:
    var db:=AudioServer.get_bus_volume_db(busIndex)
    # 返回音量的线性值
    return  db_to_linear(db)

# 设置音量
func setVolume(busIndex:int,v:float)->void:
    # 线性值转音量
    var db:=linear_to_db(v)
    AudioServer.set_bus_volume_db(busIndex,db)
